import axios from 'axios';
import { writeFile } from "fs";
import { exec } from 'child_process';
import { Client } from 'node-scp'
import { Db, MongoClient, ObjectId } from "mongodb";
let collection = null;

init();

async function init() {
    const link = "mongodb://admin:jsz04005301@120.48.63.39:27017";
    const client = new MongoClient(link);
    await client.connect();
    console.log("Connected successfully to server!");
    const db = client.db("book");
    collection = db.collection("video");
}

export async function saveImage(url: string) {
    try {
        const res = await axios.get(url, { responseType: 'arraybuffer' });
        const name = Date.now() + ".jpg";
        console.log("name", name)
        const suc = await saveFile("/root/vol/" + name, res.data);
        if (suc) {
            const localfile = "/root/vol/" + name;
            const remoterfile = "/root/www/proxy/images/" + name;
            await sendToServer(localfile, remoterfile);
            // updateDB(name, src, size);
            let t = await collection.updateOne({ poster: url }, { $set: { pic: name } });
            console.log("###更新数据###");
            console.log(t);
            return name;
        }
        return "";
    }
    catch (e) {
        console.log(e);
        return "0";
    }

}

//下载并更新数据库
export function saveVideo(video: string, src: string, size: string) {
    const name = Date.now() + ".mp4";
    console.log("name", name)
    const outputFileName = '/root/vol/' + name;
    let i = 0;
    exec(`wget ${video} -O ${outputFileName}`, async (error, stdout, stderr) => {
        ++i;
        if (error) {
            console.error(i + `#执行错误： ${error}`);
            return;
        }
        console.log(i + `#stdout: ${stdout}`);
        console.error(i + `#stderr: ${stderr}`);
        console.log("###下载成功###")

        const localfile = "/root/vol/" + name;
        const remoterfile = "/root/www/proxy/videos/" + name;
        await sendToServer(localfile, remoterfile);
        updateDB(name, src, size);
    });
    return name;
}



async function updateDB(name: string, src: string, size: string) {
    // const link = "mongodb://admin:jsz04005301@120.48.63.39:27017";
    // const client = new MongoClient(link);
    // await client.connect();
    // console.log("Connected successfully to server!");
    // const db = client.db("book");
    // const collection = db.collection("video");
    const res = await collection.updateOne({ src: src }, { $set: { name: name, size: size } });
    console.log("###更新数据成功###");
    console.log(res);
    // const temp = await collection.find({ img: { $exists: false } }).toArray();
    // const total = temp.length;
    // console.log("total", total);
    // let i = 0;

    // do {
    //     const obj = await collection.find({ img: { $exists: false } }).limit(1).toArray();
    //     console.log(i, "start");
    //     console.log(obj);

    //     if (obj.length) {
    //         const name = await download(obj[0].poster);
    //         console.log(name);

    //         await collection.updateOne({ _id: new ObjectId(obj[0]._id) }, { $unset: { pic: "" }, $set: { img: name } });
    //         // console.log("2 type of ", typeof res);
    //         // console.log(JSON.stringify(res));
    //         console.log(i + "/" + total + " ---- over")
    //     }
    //     else {
    //         break;
    //     }
    // } while (++i <= total)

}

// const url = 'https://video.twimg.com/ext_tw_video/1494279082082775048/pu/vid/324x270/aMvpiOaEAMlIvlmb.mp4?tag=12';
// const outputFileName = '/root/vol/kkkkk.mp4';

// exec(`wget ${url} -O ${outputFileName}`, (error, stdout, stderr) => {
//     if (error) {
//         console.error(`执行错误： ${error}`);
//         return;
//     }
//     console.log(`stdout: ${stdout}`);
//     console.error(`stderr: ${stderr}`);
// });

function saveFile(name, data) {
    return new Promise(resolve => {
        writeFile(name, data, err => {
            if (err) {
                console.error(err);
                resolve(false);
                return;
            }
            resolve(true)

        });
    });
}


const remoterfile = "/root/www/proxy/videos/ssstwitter.com_1705598774763.mp4"
const localfile = "/Users/sizhijiang/Downloads/ssstwitter.com_1705598774763.mp4"

export function sendToServer(localfile, remoterfile) {
    return new Promise(resolve => {
        Client({
            host: '120.48.63.39',
            port: 22,
            username: 'root',
            password: 'Jsz!0400530119',
            // privateKey: fs.readFileSync('./key.pem'),
            // passphrase: 'your key passphrase',
        }).then(client => {
            client.uploadFile(
                localfile,
                remoterfile,
                // options?: TransferOptions
            )
                .then(response => {
                    console.log("####上传服务器成功####")
                    console.log(response)
                    client.close() // remember to close connection after you finish
                    resolve(true);
                })
                .catch(error => {
                    console.log("####上传服务器失败####")
                    console.log(error)
                    resolve(false)
                })
        }).catch(e => {
            console.log("####上传服务器异常####")
            console.log(e)
            resolve(false)
        })
    });

}